package com.lby.graduation.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Map;

@Component
public class JwtUtils {
    /*秘钥*/
    private static String secret="lby234#$%";
    /*生产token*/
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        //payload
        //通过 lambda 表达式使用 forEach()
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //Calendar.getInstance()获取指定时间点(定时)
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);//默认令牌7天过期
        builder.withExpiresAt(instance.getTime());//指定令牌过期时间
        String token = builder.sign(Algorithm.HMAC256(secret));//签名
        return token;
    }
    /*验证token*/
    public static DecodedJWT verify(String token){
        //如果有任何验证异常，此处都会抛出异常
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return  decodedJWT;
    }


}
